package com.chinaums.xm.wechat.service;

import java.util.Optional;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.chinaums.xm.wechat.domain.juhe.CertInfo;
import com.chinaums.xm.wechat.domain.juhe.PhoneInfo;

import net.sf.json.JSONObject;

/**
 * 聚合数据service
 * @author chenjf
 *
 */
@Service
public class AggregationService {

	private static final Logger logger = LoggerFactory.getLogger(Communicator.class);
	
	/*邮政编码查询参数*/
	public static final String ZIP_QUERY_APPKEY = "d910a2c18b41f42c879c8604eb74ae3a";
	public static final String ZIP_QUERY_URL = "http://v.juhe.cn/postcode/query?postcode=postcode&key=申请的KEY";
	
	/*证件查询参数*/
	public static final String CERT_INFO_QUERY_APPKEY = "56914ae9c142685cb07118ab78a44492";
	public static final String CERT_INFO_QUERY_URL = "http://apis.juhe.cn/idcard/index?key=KEY&cardno=CARDNO";
	
	/*手机号查询参数*/
	public static final String MOBILE_INFO_QUERY_APPKEY = "edc9a37139195406b5f1cbb74d43fcf4";
	public static final String MOBILE_INFO_QUERY_URL = "http://apis.juhe.cn/mobile/get?phone=PHONE&key=KEY";
	
	@Resource
	private Communicator communicator;
	
	/**
	 * 根据手机号获取手机的归属信息
	 * @param phone
	 * @return
	 */
	public Optional<PhoneInfo> getMoboleInfo(final String phone){
		final String url = MOBILE_INFO_QUERY_URL.replace("PHONE", phone).replaceAll("KEY", MOBILE_INFO_QUERY_APPKEY);
		final Optional<String> response = communicator.getRequest(url);
		if(response.isPresent()){
			final String msg = response.get();
			final JSONObject json = JSONObject.fromObject(msg);
			if(json.getString("resultcode").equals("200")){
				final PhoneInfo phoneInfo = (PhoneInfo) JSONObject.toBean(JSONObject.fromObject(json.getString("result")),PhoneInfo.class);
				logger.info("手机号信息：{}",phoneInfo);
				return Optional.of(phoneInfo);
			}
		}
		return Optional.empty();
	}
	
	/**
	 * 根据证件号查询证件信息
	 * @param certNo
	 * @return
	 */
	public Optional<CertInfo> getCertInfo(final String certNo){
		final String url = CERT_INFO_QUERY_URL.replace("CARDNO", certNo).replaceAll("KEY", CERT_INFO_QUERY_APPKEY);
		final Optional<String> response = communicator.getRequest(url);
		if(response.isPresent()){
			final String msg = response.get();
			final JSONObject json = JSONObject.fromObject(msg);
			if(json.getString("resultcode").equals("200")){
				final CertInfo certInfo = (CertInfo) JSONObject.toBean(JSONObject.fromObject(json.getString("result")),CertInfo.class);
				logger.info("手机号信息：{}",certInfo);
				return Optional.of(certInfo);
			}
		}
		return Optional.empty();
	}
}
